package cn.tedu.ivos.base.file;

import cn.tedu.ivos.base.response.JsonResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/v1/file")
public class UploadController {
    @Value("${file-path}")
    private String dirPath;
    @PostMapping("upload")
    public JsonResult upload(MultipartFile file) throws IOException {
        //1.得到原始文件名
        String fileName = file.getOriginalFilename();
        //2.获取原始文件的后缀名
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //3.得到唯一的文件名
        fileName = UUID.randomUUID()+suffix;
        //4.指定一个磁盘路径用来保存图片,
        //String dirPath = "d:/files";
        //5.为了检索,我们可以设置一个自定义日期文件夹路径分层存储图片
        //日期格式： 2025/03/16     2025-03-16
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        //6.生产第五步要完成的对应文件夹路劲创建
        String datePath = sdf.format(new Date());
        //7.创建文件夹
        File dirFile =new File(dirPath+datePath);
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        //完整存储路径
        String filePath = dirPath+datePath+fileName;
        file.transferTo(new File(filePath));
        return JsonResult.ok(datePath+fileName);
    }
    @PostMapping("remove")
    public JsonResult remove(String imgUrl){
        System.out.println("imgUrl=" + imgUrl);
        new File(dirPath+imgUrl).delete();
        return JsonResult.ok();
    }

}
